package com.tiezhu.generics;

import sun.net.www.content.text.Generic;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通过反射将一个类型的集合中添加其他的类型元素
 */
public class InvokeDemo {
    public static void main(String[] args) {


        try {
            List<String> list = new ArrayList<>();
            list.add("a");
            Class<? extends List> listClass = list.getClass();
            Method add = listClass.getDeclaredMethod("add", Object.class);
            add.invoke(list, 1);
            System.out.println(list);

            Map<String, String> map = new HashMap<>();
            map.put("aa","11");
            Class<? extends Map> mapClass = map.getClass();
            Method method = mapClass.getDeclaredMethod("put", Object.class, Object.class);
            method.invoke(map, 22, "ss");
            System.out.println(map);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
